package com.kaifamiao.month04.day26.work;

import java.io.File;
import java.util.*;

public class Test02 {

    private static final List<String> TYPES = List.of(".jpg", ".jpeg", ".png", ".gif", ".svg", ".bmp", ".webp", ".jfif");

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        File file = new File("C:\\");
        File[] files = file.listFiles();
        ArrayList<File> fileArrayList = getPic(files);
        System.out.println(fileArrayList.size());
        System.out.println(System.currentTimeMillis() - start);
        getPicPath(fileArrayList);
    }

    public static void getPicPath(ArrayList<File> fileArrayList) {
        Scanner in = new Scanner(System.in);
        System.out.println("请输入你要查找的文件名：");
        boolean flag = false;
        String name = in.nextLine();
        for (File f : fileArrayList) {
            if (f.getName().contains(name)) {
                System.out.println("你查找的文件：" + f);
                flag = true;
            }
        }
        if (!flag){
            System.out.println("文件找不到");
        }
    }

    public static ArrayList<File> getPic(File[] files) {
        ArrayList<File> fileArrayList = new ArrayList<>(Arrays.asList(files));
        for (int i = 0; i < fileArrayList.size(); i++) {
            File f = fileArrayList.get(i);
            if (!f.isFile()) {
                File[] fs = f.listFiles();
                if (fs != null )  { // 文件夹为空
                    fileArrayList.addAll(Arrays.asList(fs));
                }
                fileArrayList.remove(i);
                i--;
            } else {
                if (!TYPES.contains(getEnd(f.getName()).toLowerCase())) {
                    fileArrayList.remove(i);
                    i--;
                }
            }
        }
//        fileArrayList.removeIf(f -> !TYPES.contains(getEnd(f.getName()).toLowerCase()));
        return fileArrayList;
    }

    /**
     * 获取文件后缀
     * @param str 文件名
     * @return 文件的后缀
     */
    private static String getEnd(String str) {
        for (int i = str.length() - 1; i >= 0; i--) {
            if (str.charAt(i) == '.') {
                return str.substring(i);
            }
        }
        return str;
    }
}
